import React, { useEffect, useRef } from "react";
import hljs from 'highlight.js';
import './index.less';
import copy from 'copy-to-clipboard';
import {message} from 'antd';
import { useIntl, getLocale} from 'umi';

const Highlight: React.FC = (props) => {
  const wrap = useRef(null);
  const intl = useIntl();

  useEffect(() => {
    if (props.children) {
      (wrap.current as never as HTMLElement).querySelectorAll('pre code').forEach((el) => {
        hljs.highlightElement(el as HTMLElement);
        [...el.parentNode!.querySelectorAll('.copy')].forEach(item=>{
          item.parentNode?.removeChild(item);
        })
        let copyBtn = document.createElement('span');
        copyBtn.innerText = intl.formatMessage({id: 'copy'});
        copyBtn.className = 'copy';
        copyBtn.onclick = function(){
          copy((el as HTMLElement).innerText);
          message.success('已复制到剪切版')
        }
        el.parentNode!.appendChild(copyBtn);
      });
    }
  }, [props.children, getLocale()])

  return <div className="markdown" ref={wrap}>
    {props.children}
  </div>
}

export default Highlight;